package cjmust;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;

public class Main {

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入需要备份的文件夹路径：");
		String path1 = sc.nextLine();
		System.out.print("请输入备份的文件夹路径：");
		String path2 = sc.nextLine();
		System.out.print("请输入crontab表达式（精确到秒）：");
		String crontab = sc.nextLine();
		CronUtil.schedule(crontab, new Task() {
		    @Override
		    public void execute() {
		        Console.log("Task excuted.");
		        backUp(path1, path2);
		    }
		});
		CronUtil.start();
	}
	
	
    public static void backUp(String filePath,String targetPath) {
		System.out.println(DateUtil.formatDateTime(new Date()) + "  备份启动，正在扫描文件...");
		// 扫描路径
		List<String> pathList = new ArrayList<String>();
		List<String> targetList = new ArrayList<String>();
		File file1 = new File(filePath);
		File file2 = new File(targetPath);
		readfile(file1.listFiles(), pathList , filePath);
		readfile(file2.listFiles(), targetList , targetPath);
		System.out.println(DateUtil.formatDateTime(new Date()) + "  扫描文件完毕，正在比较文件目录");
		// 对比路径
		List<String> filterResult = ListUtil.filter(pathList, str -> targetList.contains(str) ? null : str);
		if(filterResult.size()==0) {
			System.out.println(DateUtil.formatDateTime(new Date()) + "  未发现新增文件，备份已终止");
		}else {
			System.out.println(DateUtil.formatDateTime(new Date()) + "  目录比较完毕，发现新增文件" + filterResult.size() +"，正在复制当中...");
			// 复制文件
			for (String path : filterResult) { 
				FileUtil.copy(filePath+path, targetPath+path, false); 
			}
			System.out.println(DateUtil.formatDateTime(new Date()) + "  文件复制完成，备份完毕");
		}
    }
    
	public static void readfile(File[] files,List<String> path) {
		if (files == null) {
			return;
		}
		for(File f:files) {
			if(f.isFile()) {
				path.add(f.getAbsolutePath());
			}
			else if(f.isDirectory()) {
				readfile(f.listFiles(),path);
			}
		}
	}
	
	public static void readfile(File[] files, List<String> path, String targetPath) {
		if (files == null) {
			return;
		}
		for(File f:files) {
			if(f.isFile()) {
				path.add(f.getAbsolutePath().replace(targetPath, ""));
			}
			else if(f.isDirectory()) {
				readfile(f.listFiles(),path,targetPath);
			}
		}
	}
	
}
